package assets
{
	import away3d.textures.BitmapCubeTexture;
	
	import events.LoadedEvent;
	
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	import tool.BitmapTool;
	
	/**
	 * 早期基于一个xml文件与一张包括6个面贴图的位图组成的BitmapCubeTexture资源
	 * 现在CubeTexture直接通过AssetATF资源管理类取出
	 */	
	public class AssetCubeTexture extends EventDispatcher
	{
		///////////////////////////////////////////////
		private var loadingList:Array = new Array;
		private var currentLoadingURL:String;
		private var loader:URLLoader;
		
		private var _xml:XML;
		private var _bitmapURL:String;
		
		public function AssetCubeTexture()
		{
			loader = new URLLoader;
			loader.addEventListener(IOErrorEvent.IO_ERROR,onError);
		}
		
		private function onError(e:IOErrorEvent):void
		{
			var errorInfo:String ="没有此资源："+ currentLoadingURL;
			throw new Error(errorInfo);
		}
		
		public function load(URL:String):void
		{
			if(loadingList.indexOf(URL) > -1)return;
			
			if(Asset.resBitmapTextures[URL] == undefined)
			{
				loadingList.push(URL);
				
				if(loadingList.length==1)loadNext();
				
			}else{
				dispatchEvent(new LoadedEvent(URL,LoadedEvent.TEXTURE_COMPLETE));
			}
		}
		///////////////////////////////////////////////
		private function loadNext():void
		{
			currentLoadingURL = loadingList[0];
			loader.addEventListener(Event.COMPLETE,onXmlLoadComplete);
			loader.load(new URLRequest(currentLoadingURL));
		}
		
		private function onXmlLoadComplete(e:Event):void
		{
			_xml = new XML(loader.data);
			
			_bitmapURL = Asset.assetPath+"textures/" + String(_xml.@ima);
			
			Asset.bitmapdata.addEventListener(LoadedEvent.BITMAPDATA_COMPLETE,onloadComplete);
			Asset.bitmapdata.load(_bitmapURL);
		}
		
		private function onloadComplete(e:LoadedEvent):void
		{
			if(e.URL==_bitmapURL)
			{
				Asset.bitmapdata.removeEventListener(LoadedEvent.BITMAPDATA_COMPLETE,onloadComplete);
				
				var bmd:BitmapData = Asset.resBitmapDatas[_bitmapURL];
				var envMaps:Dictionary = BitmapTool.cutImageUseXML(bmd,_xml);
				
				Asset.resBitmapTextures[currentLoadingURL] = new BitmapCubeTexture(envMaps["posX"],envMaps["negX"],envMaps["posY"],envMaps["negY"],envMaps["posZ"],envMaps["negZ"]);
				
				Asset.disposeBitmapData(_bitmapURL);
				
				dispatchEvent(new LoadedEvent(currentLoadingURL,LoadedEvent.TEXTURE_COMPLETE));
				
				if(loadingList.length == 0)
				{
					loader.removeEventListener(Event.COMPLETE,onXmlLoadComplete);
					return;
				}
				
				loadNext();
			}
		}
		
	}
}